// 云函数入口文件 - 检查参与者是否已存在
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { activityId, participants } = event
  
  console.log('检查参与者状态:', { activityId, participants })
  
  try {
    // 验证参数
    if (!activityId || !participants || !Array.isArray(participants)) {
      console.error('参数验证失败:', { activityId, participants })
      return {
        success: false,
        message: '参数不完整'
      }
    }
    
    // 验证参与者数据格式
    for (let i = 0; i < participants.length; i++) {
      const participant = participants[i]
      if (!participant.name || !participant.phone) {
        console.error(`参与者${i}数据不完整:`, participant)
        return {
          success: false,
          message: `第${i + 1}位参与者信息不完整`
        }
      }
    }
    
    console.log(`开始查询活动${activityId}的已报名成员`)
    
    // 获取活动所有已报名成员
    const existingMembers = await db.collection('activity_members')
      .where({
        activityId: activityId
      })
      .get()
    
    console.log(`查询到${existingMembers.data.length}个已报名成员`)
    
    // 创建已报名参与者映射
    const existingMap = new Map()
    existingMembers.data.forEach(member => {
      const key = `${member.name}_${member.phone}`
      existingMap.set(key, member)
    })
    
    console.log('已报名成员映射:', Array.from(existingMap.keys()))
    
    // 分类参与者
    const newParticipants = []
    const existingParticipants = []
    
    participants.forEach(participant => {
      const key = `${participant.name}_${participant.phone}`
      if (existingMap.has(key)) {
        console.log(`参与者${participant.name}(${participant.phone})已存在`)
        existingParticipants.push(participant)
      } else {
        console.log(`参与者${participant.name}(${participant.phone})为新参与者`)
        newParticipants.push(participant)
      }
    })
    
    const result = {
      success: true,
      newParticipants: newParticipants,
      existingParticipants: existingParticipants,
      newCount: newParticipants.length,
      existingCount: existingParticipants.length
    }
    
    console.log('检查结果:', result)
    
    return result
    
  } catch (error) {
    console.error('检查参与者状态失败:', error)
    console.error('错误详情:', error.stack)
    return {
      success: false,
      message: '检查失败，请重试',
      error: error.message
    }
  }
}
